package com.haoshuang.zhouzhoubang.ui.page.order.take.record.fragment

import android.os.Bundle
import com.haoshuang.zhouzhoubang.R
import com.haoshuang.zhouzhoubang.databinding.FragmentTakeOrderRecordChildBinding
import com.haoshuang.zhouzhoubang.model.bean.TakeOrderRecordBean
import com.haoshuang.zhouzhoubang.ui.page.order.take.code.PayCodeActivity
import com.mufeng.libs.base.BaseVMFragment
import com.mufeng.libs.core.setEmptyData
import com.mufeng.libs.core.setOnItemChildClick
import com.mufeng.libs.core.setupData
import com.mufeng.libs.core.setupEmptyData
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.startPage
import com.mufeng.libs.utils.startPageForResult
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.vertical

/**
 *  下单记录
 */
class TakeOrderRecordChildFragment : BaseVMFragment<TakeOrderRecordChildViewModel, FragmentTakeOrderRecordChildBinding>() {

    companion object {
        fun getInstance(type: Int): TakeOrderRecordChildFragment {
            val fragment = TakeOrderRecordChildFragment()
            fragment.arguments = Bundle().apply {
                putInt("type", type)
            }
            return fragment
        }
    }

    private val mType: Int by lazy {
        arguments?.getInt("type") ?: 0
    }

    private val data = arrayListOf<TakeOrderRecordBean>()
    private val adapter = TakeOrderRecordAdapter(data)

    override fun initView(savedInstanceState: Bundle?) {

        binding.apply {
            refreshLayout.setOnRefreshListener {
                p = 1
                isShowing = false
                vm.getTeamOrderRecord(mType, p)
            }
            refreshLayout.setOnLoadMoreListener {
                p++
                isShowing = false
                vm.getTeamOrderRecord(mType, p)
            }

            recyclerView.vertical().adapter = adapter
            adapter.setEmptyData()
            adapter.setOnItemChildClick(id = R.id.tvLook){view, position, item ->
                if (item == null) return@setOnItemChildClick
                startPageForResult<PayCodeActivity>("orderSn" to item.order_id){code, data ->
                    refreshLayout.autoRefresh()
                }
            }
        }

    }

    override fun initData() {

    }

    override fun lazyLoadData() {
        p = 1
        vm.getTeamOrderRecord(mType, p)
    }

    override fun startObserve() {

        vm.getTeamOrderRecordData.observeState(this){
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
                binding.refreshLayout.setupEmptyData(data, adapter, p)
            }
            onSuccess {
                dismissLoading()
                binding.refreshLayout.setupData(it, data, adapter, p)
            }
        }

    }

}